﻿using Awsc.DataAcquisitionSys.Core.Model.Config;
using Awsc.DataAcquisitionSys.Core.Models.ServiceModels;
using Awsc.DataAcquisitionSys.Core.Services.DataAcquisition.DataCollectors;

namespace Awsc.DataAcquisitionSys.Core.Service.DataAcquisition.DataCollectors
{
    /// <summary>
    /// 无线压力采集器
    /// </summary>
    public class WirelessPressureCollector : ModbusTcpDataCollector
    {
        const ushort startAddress = 0;    //起始地址
        const ushort numberOfPoints = 8; //读数据长度
        public WirelessPressureCollector(DataCollectionContext dataCollectionContext) : base(dataCollectionContext)
        {
        }

        protected async override Task CollectDataInternalAsync()
        {
            ushort[] buff = ModbusMaster.ReadInputRegisters(CollectorConfig.SlaveAddress, startAddress, numberOfPoints);
            if (buff.Length == numberOfPoints)
            {
                //井口压力
                var data  = TypeConvert(buff[0], buff[1]);
                SetAISensorValue(1,data);
            }
            else
            {

            }
        }
        private float TypeConvert(ushort P1, ushort P2)
        {
            int intsign, insignrest, intexponent, intexponentrest;
            float faresult, fadigit;
            intsign = P1 / 32768;
            insignrest = P1 % 32768;
            intexponent = insignrest / 128;
            intexponentrest = insignrest % 128;
            fadigit = (float)(intexponentrest * 65536 + P2) / 8388608;
            faresult = (float)Math.Pow(-1, intsign) * (float)Math.Pow(2, intexponent - 127)
                       * (fadigit + 1);
            return faresult;
        }
        //一阶滤波
        float final = 0;
        float a = 0.75f;
        float FirstOrderFilter(float in_data)
        {
            final = a * in_data + (1 - a) * final;
            return (final);
        }
    }
}
